import { Controller, Get } from '@nestjs/common';
import {
  Crud,
  CrudAuth,
  CrudController,
  CrudRequest,
  CrudRequestInterceptor,
  GetManyDefaultResponse,
  Override,
  ParsedRequest,
} from '@dataui/crud';

import { TestingMachine } from '@/testing-machine/entities/testing-machine.entity';
import { TestingMachineService } from './testing-machine.service';
import { responseMessage } from '@/utils';
import { UseInterceptors } from '@nestjs/common/decorators';
import { compareTimes } from '@/utils/time';

@Crud({
  model: {
    type: TestingMachine,
  },
  query: {
    sort: [
      {
        field: 'id',
        order: 'ASC',
      },
    ],
    alwaysPaginate: true,
    join: {
      user: {
        eager: true,
        required: true,
      },
      'user.roles': {
        eager: true,
      },
      everydayDatas: {
        eager: true,
      },
      'everydayDatas.fileUploads': {
        eager: true,
      },
    },
  },
})
@CrudAuth({
  property: 'user',
})
@Controller('testing-machine')
export class TestingMachineController
  implements CrudController<TestingMachine>
{
  constructor(public service: TestingMachineService) {}

  @Override()
  async getMany(@ParsedRequest() req: CrudRequest): Promise<any> {
    const many = (await this.service.getMany(
      req,
    )) as GetManyDefaultResponse<TestingMachine>;

    return responseMessage(many);
  }

  @UseInterceptors(CrudRequestInterceptor)
  @Get('getTests')
  async getTests(@ParsedRequest() req: CrudRequest) {
    const totalData = (await this.service.getMany(
      req,
    )) as GetManyDefaultResponse<TestingMachine>;
    const tests = totalData.data;
    const auth = req.auth as { id: number; username: string; roles: string[] };
    let filterArr = tests.filter((test) => {
      return (
        auth.roles.includes('admin') ||
        test.user.id == auth.id ||
        test.user.companyParent == auth.id
      );
    });
    filterArr = filterArr.map((item) => {
      const seleTime = item.everydayDatas.sort((a, b) => {
        return (
          new Date(b.uploadDate).getTime() - new Date(a.uploadDate).getTime()
        );
      });
      const seleData = seleTime[0];
      if (seleData && seleData.fileUploads && seleData.fileUploads.length > 0) {
        seleData.fileUploads = seleData.fileUploads.sort((a, b) => {
          return compareTimes(a.uploadTime, b.uploadTime);
        });
        item.everydayDatas = [seleData];
      }

      return item;
    });
    return filterArr;
  }
}
